package com.yihong.portalserver.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @ClassName SecuringRequestInterceptor
 * @Description 微服务之间调用需要加入该配置类，使用feign发送请求时携带本次请求的头信息
 * @Author 孟志浩
 * @Date 2019/3/19 16:39
 **/
@Component
public class SecuringRequestInterceptor implements RequestInterceptor {

    /**
      * 使用feign发送请求时携带本次请求的头信息。
      * 比如登录信息的传递，需要获取头中的Authorization解析token即可获取用户id
      * @param requestTemplate
      * @return void
      * @author 孟志浩
      * @date 2019/3/19
      **/
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }
    }

}
